<template>
  <div class="article-wrapper"> 
    <div class="article-header">
      <h2>{{article.articleTitle}}</h2>
      <div class="desc">
        <span style="margin-right: 10px;">作者：{{article.articleMasterName}}</span>
        <span>发布时间：{{article.articleModifytime}}</span>
      </div>
      <div class="article w-e-text" v-html="article.articleContent"></div>
      <div class="file-list" v-if="article.articleAttachment.length > 0">
        <div class="file-left">
          附件：
        </div>
        <div class="file-right">
          <div v-for="file in article.articleAttachment" :key="file.uid">
            <a @click="downloadFile()">{{file.name}}</a>
          </div>
        </div>
      </div>
    </div>
    <div class="comment-show-wrapper">
      <h3>用户评论</h3>
      <div class="comment-show-list">
        <div v-for="comment in commentsList" :key="comment.id" class="comment-show-item">
          <div class="avatar"><img :src="comment.avatar" alt=""></div>
          <div class="comment-show-detail">
            <p class="user-name">{{comment.reviewMasterName}}</p>
            <p class="content" style="white-space: pre-line;">{{comment.reviewContent}}</p>
            <div style="padding-left: 0;margin-top: 10px;border-top: 1px dashed #ECECEC;padding-top: 10px;" class="file-list" v-if="comment.reviewAttachment.length > 0">
              <div class="file-left">
                附件：
              </div>
              <div class="file-right">
                <div v-for="file in comment.reviewAttachment" :key="file.uid">
                  <a @click="downloadFile(file.url, file.name)" href="#">{{file.name}}</a>
                </div>
              </div>
            </div>
            <p class="comment-action clearfix">
              <span>{{comment.reviewCreatetime}}</span>
              <span class="btns">
                <span v-if="comment.reviewMasterId === userInfo.dingId" @click="editReply(comment)"><i class="el-icon-edit"></i>编辑</span>
                <span v-if="comment.reviewMasterId !== userInfo.dingId" @click="openReply(comment.id)"><img style="width:12px;vertical-align:baseline;" src="../../../assets/img/reply.png">回复</span>
                <span v-if="comment.reviewMasterId === userInfo.dingId || isMg" @click="delReply(false,comment)"><i class="el-icon-delete"></i>删除</span>
              </span>
            </p>
            <div class="feedback-list" v-if="comment.childComment && comment.childComment.length > 0">
              <div class="feedback-item" v-for="childComment in comment.childComment" :key="childComment.id">
                <div class="feedback-content" style="position:relative;">
                  <div>
                    <span class="name-class">{{childComment.reviewMasterName}}：</span><span v-if="childComment.reviewNoticeUser">回复<span class="name-class">&nbsp;{{childComment.reviewNoticeUser}}：</span></span>
                    <span style="white-space: pre-line;">{{childComment.reviewContent}}</span>
                  </div>
                </div>
                <div class="feedback-action">
                  <span>{{childComment.reviewCreatetime}}</span>
                  <span class="btns">
                    <span v-if="childComment.reviewMasterId !== userInfo.dingId" @click="openReply(comment.id, childComment.reviewMasterName)"><img style="width:12px;vertical-align:baseline;" src="../../../assets/img/reply.png">回复</span>
                    <span v-if="childComment.reviewMasterId === userInfo.dingId" @click="editReply(childComment, comment.id)"><i class="el-icon-edit"></i>编辑</span>
                    <span v-if="childComment.reviewMasterId === userInfo.dingId || isMg" @click="delReply(true,childComment,comment)"><i class="el-icon-delete"></i>删除</span>
                  </span>
                </div>
              </div>
            </div>
            <div style="height: 26px;line-height: 26px;text-align:center;background:#f5f5f5;color:#999;" v-if="comment.childComment && comment.childComment.length === 3 && !comment.showAllChild" class=""><span style="cursor:pointer;" @click="getAllChildComment(comment)">查看全部回复</span></div>
          </div>
        </div>
        <p v-if="!isShowAllCommment && commentsList.length === 3"  class="comment-showAll"><span @click="openAllComment">查看全部评论</span></p>
      </div>
    </div>
    <div class="action-bar" :style="{'paddingBottom': bottomBarHeight + 'px'}">
      <div class="input-btn">
        <span @click="openReply('')">
          <i class="el-icon-edit-outline"></i>
          我来说两句
        </span>
      </div>
      <div class="like">
        <img v-if="article.likeStatus === '0'" @click="likeCollect('0','1')" src="../../../assets/img/like.png">
        <img v-if="article.likeStatus === '1'" @click="likeCollect('0','0')" src="../../../assets/img/like2.png">
      </div>
      <div class="collect">
        <img v-if="article.collectionStatus === '0'" @click="likeCollect('1','1')" src="../../../assets/img/collection.png">
        <img v-if="article.collectionStatus === '1'" @click="likeCollect('1','0')" src="../../../assets/img/collection2.png">
      </div>
      <div class="zf">
        <div @click="share(article.id, article.articleTitle)"><img src="../../../assets/img/share2.png" alt=""></div>
      </div>
    </div>
    <div v-if="showRp" class="reply-page">
      <div class="reply-header">
        <i class="el-icon-close icon" @click="showRp = false;"></i>
        评论发表
        <span class="btn" :class="{'allow': cansend}" @click="sendComment">发表</span>
      </div>
      <div class="mobile-input-wp">
        <el-input style="width: 100%;" ref="mbinput" autofocus="true" @input="detectInput" rows="8" v-model="myComment" type="textarea"></el-input>
      </div>
      <div>
        <input style="display:none;" type="file" @change="uploadFile($event, myCommentAttachment)" multiple="multiple">
        <span class="addfilebtn" @click="openUpload($event)"><i class="el-icon-paperclip"></i>添加附件</span>
      </div>
      <div class="fileitem" style="padding: 0 10px;" v-for="(file, idx) in myCommentAttachment" :key="idx">
        <span style="cursor: pointer;color: #45c2b5;" @click="downloadFile(file.url, file.name)">
          {{file.name}}
        </span>
        <span class="uploadtip" style="cursor:pointer;" v-if="file.url" @click="delFile(idx, myCommentAttachment)"><i class="el-icon-delete"></i></span>
        <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
      </div>
    </div>
  </div>
</template>

<script>


import sinaEmotions from '@/assets/emotion/sina'
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import AtTa from 'vue-at/dist/vue-at-textarea'

export default {
  name: 'Article',
  data () {
    return {
      myComment:'',
      myCommentAttachment: [],
      members: [],
      showRp: false,
      showReply: false,
      article: {
        sectionId: '',
        articleTitle: '',
        articleMasterId: '',
        articleMasterName: '',
        articleInfo: '',
        articleContent: '',
        articleStatus: '',
        articleAttachment: [],
        articleCount: '',
        articleLikecount: '',
        articleCreatetime: '',
        articleModifytime: '',
        collectionStatus: '0',
        likeStatus: '0',
        id: '',
      },
      commentsList: [],
      editorContainer: {},
      isShowAllCommment:false,
      bottomBarHeight: 10,
      commentCache: [],
    }
  },
  components:{
      AtTa
  },
  mixins: [dingMixin],
  computed: {
    cansend () {
      return this.myComment.length > 0
    },
  },
  async mounted() {
    this.mobileStopRefresh();
    this.mobileHiddenRightMenu();
    this.mobileGetDevice(({model, brand, version}) => {
      if(brand === 'iPhone' && ( model.indexOf('10') > 0 || model.indexOf('11') > 0)) {
        this.bottomBarHeight = 30;
      }
    })
    let article = await this.$httpN.get('community/article/info/' + this.$route.params.id);
    if(article.articleStatus !== '1') {
      return this.mobileAlert('文章已被删除，请返回', async () => {
        if(!await this.$httpN.postB('community/likecollection/like', {
          userId: this.userInfo.dingId,
          contextId: article. 
          id,
          dataType: 1,
          status: 0
        })) return
        this.$router.go(-1)
      })
    }
    article.articleAttachment = JSON.parse(article.articleAttachment);
    this.article = article;
    this.getComment();
    this.loadMembers().then(data=>this.members = data);
  },
  methods:{
    delFile(idx,target){
      target.splice(idx, 1)
    },
    openUpload(el){
      el.target.parentNode.firstChild.click()
    },
    async uploadFile(e, target) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
        }
        target.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            target.pop();
          }
        })
      })
      e.target.value = '';
    },
    openReplyModel (){
      this.showRp = true;
      this.myComment = '';
      this.myCommentAttachment = [];
      this.commentCache = [...arguments]
    },
    openEditReply (text, attachment, agr) {
      this.showRp = true;
      this.myComment = text;
      this.myCommentAttachment = formUtil.deepCopy(attachment)
      this.commentCache = [...agr]
    },
    detectInput() {
      if(this.myComment.charAt(this.myComment.length - 1) === '@'){
        this.complexPicker(1).then((data)=>{
          this.myComment += data[0].name + ' '
        })
      }
    },
    sendComment() {
      if(!this.cansend) return;
      this.reply2(this.commentStatus, this.myComment, ...this.commentCache)
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) {
         return this.dingPreviewPic(url);
      }else{
        this.mobileAlert('手机不支持下载文件，请到电脑端下载');
      }
    },
    async likeCollect(type, status){
      if(!await this.$httpN.postB('community/likecollection/like', {
        userId: this.userInfo.dingId,
        contextId: this.article.id,
        contextTitle: this.article.articleTitle,
        dataType: type,
        status: status
      })) return

      this.mobileMessage((status === '0'? '取消': '') + (type === '0'? '点赞': '收藏') + '成功')
      if(type === '0') {
        this.article.likeStatus = status;
      }else if(type === '1') {
        this.article.collectionStatus = status;
      }
    },
    openReply(replyId,reviewNoticeUser) {
      this.commentStatus = false;
      this.openReplyModel(replyId, reviewNoticeUser);
    },
    editReply(comment, parentCommentId) {
      this.commentStatus = true;
      this.openEditReply(comment.reviewContent, comment.reviewAttachment, [comment.id, parentCommentId]);
    },
    async reply2(isEdit, text, replyId, reviewNoticeUser) {
      if(!isEdit) {
        if(! await this.$httpN.postB('community/review/save', {
          articleId: this.article.id,
          replyReviewId: replyId? replyId: '',
          reviewContent: text,
          reviewAttachment: this.myCommentAttachment,
          reviewMasterId: this.userInfo.dingId,
          reviewMasterName: this.userInfo.realName,
          reviewNoticeUser: reviewNoticeUser? reviewNoticeUser: '',
          content: this.article.articleTitle,
          url: this.article.id
        })) return 
        
        this.getComment(replyId);
      }else{
        if(! await this.$httpN.postB('community/review/update', {
          reviewAttachment: this.myCommentAttachment,
          id: replyId,
          reviewContent: text,
        })) return 
        this.mobileMessage('编辑成功');
        this.getComment(reviewNoticeUser);
      }
      this.showRp = false;
    },
    delReply(isChild,comment,parentComment) {
      this.mobileConfirm('此操作将永久删除评论及评论下的回复, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/review/delete', {ids: comment.id}, false)) return;
        this.mobileMessage('删除成功');
        if(!isChild) {
          this.getComment();
        }else {
          this.getAllChildComment(parentComment);
        }
    })
    },
    async openAllComment() {
      this.isShowAllCommment = true;
      let result = await this.$httpN.postB('community/review/list', {page: 2, dataType:0, articleId: this.article.id})
      result.forEach(element => {
        element.childComment = [];
        element.showAllChild = false;
        element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
      });
      this.commentsList = result;
      let commentsId = result.map(item => item.id)
      this.getSomeChildComment(commentsId.join(','))
    },
    async getComment(replyId) {
      if(!replyId) {
        this.isShowAllCommment = false;
        this.getParentComment();
      }else {
        this.getAllChildComment({id: replyId});
      }
    },
    async getAllChildComment(comment) {
      comment.showAllChild = true;
      let childComment = await this.$httpN.postB('community/review/list', {page: 2,dataType: 1,articleId: this.article.id, replyReviewIds: comment.id});
      this.commentsList.forEach((item) => {
        if(item.id === comment.id){
          item.childComment = childComment[comment.id];
        }
      })
    },
    async getSomeChildComment(ids) {
      let childComment = await this.$httpN.postB('community/review/list', {page: 1,dataType: 1,articleId: this.article.id, replyReviewIds: ids})
      for(let parentId in childComment) {
        this.commentsList.forEach((parent) => {
          if(parent.id === parentId) parent.childComment.push(...childComment[parentId])
        })
      }
    },
    async getParentComment() {
      let result = await this.$httpN.postB('community/review/list', {page: 1,dataType: 0,articleId: this.article.id})
      result.forEach(element => {
        element.childComment = [];
        element.showAllChild = false;
        element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
      });
      this.commentsList = result;
      let commentsId = this.commentsList.map(item => item.id);
      this.getSomeChildComment(commentsId.join(','))
    },
    share() {
      this.complexPicker(1).then(async (data) => {
        if(!await this.$httpN.postB('community/article/share', {
          usernames: '@' + data[0].name,
          content: this.article.articleTitle,
          url: this.article.id
        })) return;
        this.mobileMessage('分享成功');
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .reply-header{
    line-height: 44px;
    background: #FFF;
    text-align: center;
    font-weight: bold;
    color: #999;
    position: relative;
    border-top: 1px solid #e8e8e8;
    .icon{
      position: absolute;
      top: 10px;
      left: 15px;
      font-size: 25px;
      font-weight: bold;
    }
    .btn{
      position: absolute;
      top: 10px;
      right: 15px;
      color: #FFF;
      background: #DFE3E8;
      line-height: 20px;
      border-radius: 4px;;
      padding: 5px 10px;
      line-height: 1;
    }
    .allow{
      background: #484747;
    }
  }
  .mobile-input-wp{
    padding: 10px;
  }
  .article-wrapper{
    position: relative;
    min-height: 100vh;
    background: #F6F6F6;
    padding-bottom: 55px;
    .article-header{
      background: #fff;
      padding: 20px 20px;
      h2{
        margin: 0;
        font-size: 18px;
      }
      .desc{
        margin-top: 20px;
        font-size: 14px;
        color:#909AA4;
      }
      .article{
        margin-top: 20px;
        font-size:15px;
      }
      .file-list{
        margin-top: 30px;
        display: flex;
        .file-left{
          width: 45px;
        }
        .file-right{
          flex: 1;
          >div{
            margin-bottom: 5px;
          }
        }
      }
    }
    .comment-show-wrapper{
      padding: 20px 20px;
      background: #FFF;
      margin-top: 10px;
      h3{
        margin: 0;
        font-size: 16px;
        font-weight: bold;
      }
      .comment-showAll{
        margin: 0;
        margin-top: 20px;
        text-align: center;
        color: #999;
      }
      .comment-show-list{
        margin-top: 10px;
        .comment-show-item{
          padding: 12px 0 10px;
          border-bottom: 1px solid #e8e8e8;
          margin-left: 40px;
          position: relative;
          .avatar{
            position: absolute;
            top:10px;
            left:-35px;
            img{
              width: 25px;
              height: 25px;
              border-radius: 100%;
              display:block;
            }
          }
          .comment-show-detail{
            word-break: break-all;
            p{
              margin: 0;
            }
            .user-name{
              font-weight: bold;
            }
            .content{
              margin-top: 10px;
            }
            .comment-action{
              margin-top: 10px;
              font-size: 12px;
              color: #999;
              position: relative;
              .btns{
                float: right;
                span{
                  margin-left:5px;
                }
              }
            }
            .feedback-list{
              margin-top: 5px;
              background: #f5f5f5;
              border-radius: 5px;
              .feedback-item{
                padding: 10px 12px;
                border-bottom: 1px solid #e8e8e8;
                &:last-child{
                  border: none;
                }
                .feedback-content{
                  font-size: 14px;
                  span.name-class{
                    font-weight: bold;
                  }
                }
                .feedback-action{
                  margin-top: 5px;
                  position: relative;
                  font-size: 12px;
                  text-align: left;
                  color: #999;
                  .btns{
                    float: right;
                    span{
                      cursor: pointer;
                      margin-left:5px;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    .action-bar{
      position: fixed;
      box-shadow: 0 0 10px 0 hsla(0,6%,58%,.6);
      background: #FFF;
      bottom: 0;
      left: 0;
      padding: 10px;
      width: 100%;
      display: flex;
      >div:first-child{
        flex: 1;
        margin-right: 40px;
        span{
          display:inline-block;
          width: 100%;
          color: rgb(135, 135, 135);
          background: rgb(246, 247, 249);
          height: 100%;
          border-radius: 30px;
          padding-left: 10px;
          line-height: 25px;
        }
      }
      div.like,.collect,.zf{
        width: 40px;
        text-align: center;
        img{
          width: 20px;
        }
      }
    }
  }
  .reply-page{
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100%;
    background: #F6F6F6;
  }
  .file-list{
    margin-top: 30px;
    display: flex;
    .file-left{
      width: 45px;
    }
    .file-right{
      flex: 1;
      >div{
        margin-bottom: 5px;
      }
    }
  }
  .addfilebtn{
    margin-left: 10px;
  }
</style>